﻿using System;

namespace CommonEngine.Tools
{
    /// <summary>
    /// 自定义的堆栈---后进先出
    /// </summary>
    public class AppStack<T>
    {
        private class Entry<K>
        {
            public Entry<K> next;
            public K data;
            public Entry(Entry<K> en, K obj)
            {
                this.next = en;
                this.data = obj;
            }
        }

        Entry<T> top = null;
        private int num = 0;

        public bool hasData
        {
            get { return (this.num > 0); }
        }

        public int StackNum
        {
            get { return this.num; }
        }

        /// <summary>
        /// 入栈
        /// </summary>
        public void Push(T data)
        {
            this.top = new Entry<T>(top, data);
            num++;
        }

        /// <summary>
        /// 出栈
        /// </summary>
        public bool Pop(out T t)
        {
            if (this.top == null)
            {
                t = default(T);
                num = 0;
                return false;
            }
            t = top.data;
            top = top.next;
            num--;

            return true;
        }

        public T Pop()
        {
            T result = default(T);
            if (this.Pop(out result))
                return result;
            else
            {
                if (typeof(T) == typeof(DateTime))
                    return (T)((object)DateTime.Now);
                else
                    return default(T);
            }
        }

    }
}
